import { Injectable, Injector } from '@angular/core';
import { PlatformLocation } from '@angular/common';
import { Router } from '@angular/router';
import { StoreService } from './store.service';

@Injectable({
  providedIn: 'root'
})
export class AppService<U, B, S> {

  constructor(
    private location: PlatformLocation,
    private storeService: StoreService<B, S>,
    private injector: Injector
  ) { }

  /**
   * 重置session数据一般在应用初次启动或者正常请求接口时发现会话失效时执行
   */
  public storeSession() {
    const session = this.storeService.getItem(<any>'Session') || {};
    let lastUrl = window.location.pathname.replace(this.location.getBaseHrefFromDOM(), '');

    lastUrl = lastUrl.startsWith('/') ? lastUrl : '/' + lastUrl;
    session.lastUrl = lastUrl + window.location.search;

    this.storeService.setItem(<any>'Session', session);
  }

  /**
   * 一般用在会话正确初始化之后导航到用户主页
   * @param homePath 主页地址
   */
  public navigateHome(homePath: string) {
    const router = this.injector.get(Router);
    const session = this.storeService.getItem(<any>'Session') || {};
    // 首次进入系统的页面
    const lastUrl = session.lastUrl;
    // 当前页面
    const currUrl = router.url;

    if (lastUrl) {
      // 避免循环跳转
      if (currUrl.includes(lastUrl) || lastUrl.includes(currUrl)) {
        router.navigate([homePath], { queryParams: { _closeable: 'false', _fixed: 'true' } });
      } else {
        router.navigateByUrl(lastUrl);
      }
    } else {
      router.navigate([homePath], { queryParams: { _closeable: 'false', _fixed: 'true' } });
    }
  }
}
